package com.linghang.wusthelpercompetition.controller;

import com.github.houbb.sensitive.word.core.SensitiveWordHelper;
import com.linghang.wusthelpercompetition.dto.CompetitionDTO;
import com.linghang.wusthelpercompetition.dto.CompetitionPostPageDTO;
import com.linghang.wusthelpercompetition.dto.CompetitionPostUpdateDTO;
import com.linghang.wusthelpercompetition.entity.CompetitionPost;
import com.linghang.wusthelpercompetition.entity.ResponsePost;
import com.linghang.wusthelpercompetition.mapper.CompetitionPostMapper;
import com.linghang.wusthelpercompetition.mapper.ResponsePostMapper;
import com.linghang.wusthelpercompetition.result.PageResult;
import com.linghang.wusthelpercompetition.result.Result;
import com.linghang.wusthelpercompetition.service.CompetitionPostService;
import com.linghang.wusthelpercompetition.service.ResponsePostService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.annotations.Delete;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

import static com.linghang.wusthelpercompetition.utils.GetIdentityService.getUidFromSecurityContext;


@RestController
@RequestMapping("/competitionPost")
@Tag(name = "竞赛帖子相关接口")
@Slf4j
public class CompetitionPostController {

    @Autowired
    private ResponsePostService responsePostService;

    @Autowired
    private CompetitionPostService competitionPostService;



    /**
     * 新建一个帖子
     * @return
     */
    @PostMapping
    @Operation(summary = "新建一个帖子")
    public Result<String> addPost(@RequestBody CompetitionDTO competitionDTO) {
        String StudentId = getUidFromSecurityContext();
        String competitionName = competitionDTO.getCompetitionName();
        String competitionIntroduction = competitionDTO.getCompetitionIntroduction();
        String requirement = competitionDTO.getRequirement();
        String contactInformation = competitionDTO.getContactInformation();
//        if(competitionName == null || competitionIntroduction == null || requirement == null || contactInformation == null){
//            return Result
//        }
        if(SensitiveWordHelper.contains(competitionName)||SensitiveWordHelper.contains(competitionIntroduction)||SensitiveWordHelper.contains(requirement)||SensitiveWordHelper.contains(contactInformation)){
            return Result.error("内容包含敏感词!");
        }
        Long total = competitionPostService.getTotalByStudentId(StudentId);
        if(total >= 10){
            return Result.error("最多只能同时发布10个帖子,请先删除");
        }
        competitionDTO.setStudentId(StudentId);
        log.info("新建一个帖子：{}", competitionDTO);
        competitionPostService.save(competitionDTO);
        return Result.success();
    }

    /**
     * 删除一个帖子，根据cid
     * @return
     */
    @DeleteMapping("/{cid}")
    @Operation(summary = "删除一个帖子")
    public Result deletePost(@PathVariable long cid) {

        log.info("删除一个帖子：{}", cid);
        //判断这个帖子是不是自己的，如果是自己的帖子才可以删除
        String studentId = getUidFromSecurityContext();
        CompetitionPost competitionPost = competitionPostService.getByCid(cid);
        if(!studentId.equals(competitionPost.getStudentId() ) ){
            return Result.error("权限不够，不能删除别人的帖子");
        }


        if(competitionPostService.getByCid(cid)==null){
            return Result.error("帖子不存在");
        }
        competitionPostService.deleteByCid(cid);
        //删除帖子后，已结所有回复
        List<ResponsePost> list = responsePostService.listResponsesByPost(cid);
        for (ResponsePost responsePost : list) {
            responsePostService.deleteResponse(responsePost.getRid());
        }
        return Result.success();
    }

    /**
     * 修改帖子
     * @return
     */
    @PutMapping
    @Operation(summary = "修改帖子")
    public Result updatePost(@RequestBody CompetitionPostUpdateDTO competitionPostUpdateDTO ) {
        log.info("修改帖子：{}", competitionPostUpdateDTO);
        //如果帖子非自己的则不能修改
        String studentId = getUidFromSecurityContext();
        CompetitionPost competitionPost = competitionPostService.getByCid(competitionPostUpdateDTO.getCid());
        if(!studentId.equals(competitionPost.getStudentId() ) ){
            return Result.error("权限不够，不能修改别人的帖子");
        }

        String competitionName = competitionPostUpdateDTO.getCompetitionName();
        String competitionIntroduction = competitionPostUpdateDTO.getCompetitionIntroduction();
        String requirement = competitionPostUpdateDTO.getRequirement();
        String contactInformation = competitionPostUpdateDTO.getContactInformation();
        if(SensitiveWordHelper.contains(competitionName)||SensitiveWordHelper.contains(competitionIntroduction)||SensitiveWordHelper.contains(requirement)||SensitiveWordHelper.contains(contactInformation)){
            return Result.error("内容包含敏感词!");
        }
        if(competitionPostService.getByCid(competitionPostUpdateDTO.getCid())==null){
            return Result.error("帖子不存在");
        }
        competitionPostService.update(competitionPostUpdateDTO);
        return Result.success();
    }

//    /**
//     * 帖子超时15天自动删除
//     * 这个请求每天一次调用,确保定时查看帖子是否超时
//     * @return
//     */
//    @DeleteMapping("/timeout")
//    public Result timeoutPost(){
//        competitionPostService.timeoutPost();
//        return Result.success("帖子已超时");
//    }


    /**
     * 分页查询帖子
     * @return
     */
    @PostMapping("/page")
    @Operation(summary = "分页查询帖子,status参数1表示查询自身的  0表示查询所有的，2表示查询回复过的所有帖子 ，studentID不用传")
    public Result<PageResult> page(@RequestBody CompetitionPostPageDTO competitionPostPageDTO){
        competitionPostPageDTO.setStudentId(null);
        if(competitionPostPageDTO.getStatus() == 1){
            String studentId = getUidFromSecurityContext();
            competitionPostPageDTO.setStudentId(studentId);
        }
        if(competitionPostPageDTO.getStatus() == 2){
            String studentId = getUidFromSecurityContext();
           List<Long> cids = responsePostService.selectCidsByStudentId(studentId);
           List<CompetitionPost> competitionPosts = competitionPostService.selectBycids(cids);
           PageResult pageResult = new PageResult(competitionPosts.size(),competitionPosts);
           return Result.success(pageResult);
        }

        log.info("分页查询员工：{}",competitionPostPageDTO);
        PageResult pageResult = competitionPostService.pageQuery(competitionPostPageDTO);

        log.info("{}",pageResult.getRecords());
        return Result.success(pageResult);
    }


    /**
     * 根据cid查询帖子信息
     * @param cid
     * @return
     */
    @GetMapping("/{cid}")
    @Operation(summary = "根据cid查询帖子信息")
    public Result<CompetitionPost> getById(@PathVariable("cid") Long cid) {
        log.info("根据cid查询帖子：{}", cid);
        CompetitionPost competitionPost = competitionPostService.getByCid(cid);
        if(competitionPost==null){
            return Result.error("帖子不存在");
        }
        return Result.success(competitionPost);
    }









}
